<?php
namespace app\app\controller\v1;
use think\Db;
use think\Request;
use app\app\util\OnlineUtils;

require_once(dirname(dirname(dirname(__FILE__))).'/util/phpqrcode/phpqrcode.php');
use phpqrcode\QRcode;

class CouponController extends BaseController{

    /**
     * 显示资源列表
     * 我领取的优惠券列表
     * @return \think\Response
     */
    public function index()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        if(input('get.id') && input('get.id') >0){
            $page = config('PAGE_NUM').input('get.id');
        }else{
            $page = 0;
        }
    	//查询数据
    	$coupon = Db::query('select b.id,b.user_id,b.price,b.title,b.num,b.description,b.lnt,b.lgt from hmp_coupon_use a left join hmp_coupon b on a.coupon_id=b.id where a.user_id='.$user_id.' and b.status=1 order by a.id desc limit '.$page.',10');
    	if(!$coupon){
    		$coupon = [];
    	}
    	return hmp(200,'success',['data'=>$coupon]);
    }

    // 我发布的优惠券
    public function myPublishCoupon()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        if(input('get.id') && input('get.id') >0){
            $page = config('PAGE_NUM').input('get.id');
        }else{
            $page = 0;
        }
        //查询数据
        $coupon = Db::query('select a.id,a.user_id,a.price,a.title,a.num,a.description,a.lnt,a.lgt from hmp_coupon a left join hmp_users b on a.user_id=b.id where a.user_id='.$user_id.' and b.status=1 order by a.id desc limit '.$page.',10');
        if(!$coupon){
            $coupon = [];
        }
        return hmp(200,'success',['data'=>$coupon]);        
    }

    // /优惠券列表
    public function couponList()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        if(input('get.id') && input('get.id') >0){
            $page = config('PAGE_NUM').input('get.id');
        }else{
            $page = 0;
        }
        //查询数据
        $coupon = Db::query('select a.id,a.user_id,a.price,a.title,a.num,a.description,a.lnt,a.lgt from hmp_coupon a left join hmp_users b on a.user_id=b.id where a.status=1 and b.status !=0 order by a.id desc limit '.$page.',10');
        if(!$coupon){
            $coupon = [];
        }
        return hmp(200,'success',['data'=>$coupon]);        
    }   

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {

    }

    /**
     * 保存新建的资源
     * 发布优惠券
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $card_num = Db::name('card')->where('user_id','eq',$user_id)->count();
        if($card_num < 1){
            return hmp(402,'请先去发布自己的名片');
        }
        $coupon['user_id'] = $user_id;
    	$coupon['title'] = input('post.title') ? input('post.title') : '';
    	$coupon['price'] = intval(input('post.price'));
    	$coupon['num']   = intval(input('post.num'));
    	$coupon['description'] = input('post.description') ? input('post.description') : '';
		$coupon['create_time'] = date('Y-m-d H:i:s',time());
        $coupon['lnt'] = input('post.lnt') ? input('post.lnt') : '';
        $coupon['lgt'] = input('post.lgt') ? input('post.lgt') : '';
    	$id = Db::name('coupon')->insertGetId($coupon);
    	if($id){
            $data = Db::name('coupon')->where('id','eq',$id)->find();
    		return hmp(200,'success',['data'=>$coupon]);
    	}else{
    		return hmp(402,'fail');
    	}
    }

    /**
     * 显示指定的资源
     * 优惠券生成二维码
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $user_id = OnlineUtils::getUserIdBySid();
    	$id = intval(input('id'));
    	$coupon_use = Db::name('coupon_use')->where('coupon_id','eq',$id)->where('user_id','eq',$user_id)->find();
    	$coupon = Db::name('coupon')->where('id','eq',$id)->find();
    	if($coupon_use && $coupon != null){
    		$data['id'] = $coupon['id'];
    		$data['user_id'] = $coupon_use['user_id'];
			$data['coupon_id'] = $coupon_use['id'];
    		$data['title']   = $coupon['title'];
    		$data['price']   = $coupon['price'];
    		$data['description'] = $coupon['description'];
            $data['lnt'] = $coupon['lnt'];
            $data['lgt'] = $coupon['lgt'];
		    $value = $value = json_encode($data);;      //二维码内容  
		    $errorCorrectionLevel = 'L';    //容错级别   
		    $matrixPointSize = 5;           //生成图片大小    
		    //生成二维码图片
		    $name = microtime(); 
		    $filename = ROOT_PATH.'public'.DS.'/phpqrcode/'.$name.'.png';  
		    $QR = QRcode::png($value,$filename, $errorCorrectionLevel, $matrixPointSize, 2);
			$filename = config('QRcode').$name.'.png';
	    	return hmp(200,'success',['data'=>$filename]);	
    	}else{
    		return hmp(402,'优惠券不存在');
    	}
    }

    //根据优惠券ID获取详情
    public function getCouponDeatilById()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $id = input('get.id') ? input('get.id') : 0;
        $coupon = Db::name('coupon')->field('title,price,num,description,lnt,lgt')->where('id','eq',$id)->find();
        if($coupon){
            $coupon_use = Db::name('coupon_use')->where('coupon_id','eq',$id)->where('user_id','eq',$user_id)->where('status','neq',0)->find();
            if($coupon_use){
                $coupon['is_receive'] = 1;
            }else{
                $coupon['is_receive'] = 0;
            }
            return hmp(200,'success',['data'=>$coupon]);
        }else{
            return hmp(402,'fail');
        }
    }

    // 核销
    public function isChange()
    {
        $user_id = OnlineUtils::getUserIdBySid();
    	//接受参数
    	$id = intval(input('post.id'));
        $coupon_id = intval(input('post.coupon_id'));
    	//查询
        $coupon_use = Db::name('coupon_use')->where('id','eq',$coupon_id)->find();
        $coupon  = Db::name('coupon')->where('id','eq',$id)->where('user_id','eq',$user_id)->find();
    	if($coupon){
    		//存在
    		Db::query('update hmp_coupon_use set status = 2 where id= '.$coupon_id);
    		return hmp(200,'核销成功');
    	}else{
    		return hmp(402,'优惠券不存在');
    	}
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update($id)
    {

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {

    }

    //领取优惠券
    public function receiveCoupon()
    {
        $user_id = OnlineUtils::getUserIdBySid();
    	$id = intval(input('post.id'));
    	$coupon = Db::name('coupon')->where('id','eq',$id)->find();
		if($coupon['user_id'] == $user_id) return hmp(402,'无法领取自己发布的优惠券');
		$coupon_use = Db::name('coupon_use')->where('user_id','eq',$user_id)->where('coupon_id','eq',$id)->find();
		if($coupon_use) return hmp(402,'无法多次领取');
    	//优惠券存在且数量不为0
    	if($coupon && $coupon['num'] >= 1){
    		Db::name('coupon_use')->insert(array('user_id'=>$user_id,'coupon_id'=>$id));
    		Db::query('update hmp_coupon set num = num - 1 where id ='.$id);
    		return hmp(200,'success');
    	}else{
    		return hmp(402,'领取失败');
    	}
    }

}